package com.lyx.framework.utils.statusbar;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.lyx.framework.R;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

import androidx.annotation.ColorInt;

public class StatusBarUtil {

    private static final String TAG = "CtripStatusBarUtil";

    public static final String ROM_FLYME = "FLYME";
    public static final String ROM_MIUI = "MIUI";
    private static final String KEY_VERSION_MIUI = "ro.miui.ui.version.name";

    private static String sName;
    private static String sVersion;

    private static final int FAKE_TRANSLUCENT_VIEW_ID = R.id.status_bar_view;
    private static final int OFFSET_TAG =-123 ;
    private static final int DEFAULT_STATUS_BAR_ALPHA = 112;

    private static Set<OnFullScreenSetListener> onFullScreenSetListeners = new HashSet<>();

    public static boolean isTransparentStatusBarSupported(){
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M || isMiui() || isFlyme();
    }

    private static boolean isMiui() {
        return check(ROM_MIUI);
    }

    private static boolean isFlyme() {
        return check(ROM_FLYME);
    }

    public static boolean check(String rom) {
        if (sName != null) {
            return sName.equals(rom);
        }

        if (!TextUtils.isEmpty(sVersion = getProp(KEY_VERSION_MIUI))) {
            sName = ROM_MIUI;
        } else {
            sVersion = Build.DISPLAY;
            if (sVersion.toUpperCase().contains(ROM_FLYME)) {
                sName = ROM_FLYME;
            } else {
                sVersion = Build.UNKNOWN;
                sName = Build.MANUFACTURER.toUpperCase();
            }
        }
        return sName.equals(rom);
    }

    private static String getProp(String name) {
        String line;
        BufferedReader input = null;
        try {
            Process p = Runtime.getRuntime().exec("getprop " + name);
            input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
            line = input.readLine();
            input.close();
        } catch (IOException ex) {
            return null;
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return line;
    }

    public static void addOnFullScreenSetListener(OnFullScreenSetListener listener){
        if (listener != null){
            onFullScreenSetListeners.add(listener);
        }
    }

    public static void removeOnFullScreenSetListener(OnFullScreenSetListener listener){
        if (listener != null && onFullScreenSetListeners.contains(listener)){
            onFullScreenSetListeners.remove(listener);
        }
    }

    public static void clearOnFullScreenSetListeners(){
        onFullScreenSetListeners.clear();
    }

    /**
     * 设置默认状态栏
     * @param activity
     */
    public static void setDefaultStatusBarColor(Activity activity){
        setStatusBarColor(activity,Color.BLACK,0);
    }

    /**
     * 设置白色TitleBar状态栏颜色
     * @param activity
     */
    public static void setStatusBarForWhiteTitleBar(Activity activity){
        if (activity == null || activity.getWindow() == null) {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            activity.getWindow()
                    .getDecorView()
                    .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            activity.getWindow().setStatusBarColor(Color.WHITE);
            miuiSetStatusBarLightMode(activity.getWindow(), true);
            flymeSetStatusBarLightMode(activity.getWindow(), true);
        }else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            setStatusBarColor(activity,Color.GRAY,0);
        }
    }


    /**
     * 设置恢色TitleBar状态栏颜色
     * @param activity
     */
    public static void setStatusBarForGrayTitleBar(Activity activity){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            setStatusBarColor(activity,Color.GRAY,0);
        }
    }

    public static void setStatusBarForH5GrayThemeTitleBar(Activity activity){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            setStatusBarColor(activity,Color.parseColor("#f7f7f7"),0);
        }
        setLightStatuBar(activity);//灰色主题，需要设置状态栏文字颜色为黑色。否则文字看不到
    }

    /**
     * 设置蓝色TitleBar状态栏颜色
     * @param activity
     */
    public static void setStatusBarForBlueTitleBar(Activity activity){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            setStatusBarColor(activity,Color.parseColor("#0086F6"),0);
        }
    }

    /**
     * 设置状态栏颜色
     * @param activity 设置的activity
     * @param color 状态栏颜色
     */
    public static void setStatusBarColor(Activity activity,@ColorInt int color){
        setStatusBarColor(activity,color,0);
    }

    /**
     * 设置状态栏颜色
     * @param activity 设置的activity
     * @param color 状态栏颜色
     * @param alpha 透明度
     */
    public static void setStatusBarColor(Activity activity, @ColorInt int color, int alpha){
        if (activity == null || activity.getWindow() == null) {
            return;
        }
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            activity.getWindow()
                    .getDecorView()
                    .setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
            activity.getWindow().setStatusBarColor(calculateStatusColor(color,alpha));

            for (OnFullScreenSetListener listener : onFullScreenSetListeners){
                listener.onFullScreenExit();
            }
        }
    }

    /**
     * 设置状态栏颜色
     * @param activity 设置的activity
     * @param color 状态栏颜色
     * @param alpha 透明度
     * @param keepFullScreen 是否保持全屏
     */
    public static void setStatusBarColor(Activity activity, @ColorInt int color, int alpha, boolean keepFullScreen){
        if (activity == null || activity.getWindow() == null) {
            return;
        }
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            if (!keepFullScreen){
                activity.getWindow()
                        .getDecorView()
                        .setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
            }
            activity.getWindow().setStatusBarColor(calculateStatusColor(color,alpha));

            for (OnFullScreenSetListener listener : onFullScreenSetListeners){
                listener.onFullScreenExit();
            }
        }
    }

    /**
     * 创建一个和状态栏一样高的矩形View
     * @param activity
     * @param color
     * @param alpha
     * @return
     */
    private static View createStatusBarView(Activity activity, @ColorInt int color, int alpha) {
        View statusBarView = new View(activity);
        LinearLayout.LayoutParams params =
                new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(activity));
        statusBarView.setLayoutParams(params);
        statusBarView.setBackgroundColor(Color.BLUE);
        statusBarView.setId(FAKE_TRANSLUCENT_VIEW_ID);
        return statusBarView;
    }

    /**
     * 使状态栏透明
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    private static void transparentStatusBar(Activity activity) {
        if (activity == null || activity.getWindow() == null) {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            activity.getWindow().setStatusBarColor(Color.TRANSPARENT);
        } else {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    /**
     * 设置透明
     */
    public static void setTransparentForWindow(Activity activity) {
        if (activity == null || activity.getWindow() == null) {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            activity.getWindow().setStatusBarColor(Color.TRANSPARENT);
            activity.getWindow()
                    .getDecorView()
                    .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

            for (OnFullScreenSetListener listener : onFullScreenSetListeners){
                listener.onFullScreenSet();
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            activity.getWindow()
                    .setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    /**
     * 设置状态栏文字颜色为黑色 6.0以上系统有效
     * @param activity
     */
    public static void setLightStatuBar(Activity activity) {
        setStatusBarLightMode(activity,true);
    }

    /**
     * 设置状态栏文字颜色模式
     * @param activity
     * @param dark 文字是否是黑色，true为黑色，false为白色
     */
    public static void setStatusBarLightMode(Activity activity,boolean dark){
        if (isMiui()){
            miuiSetStatusBarLightMode(activity.getWindow(), dark);
        }

        if (isFlyme()){
            flymeSetStatusBarLightMode(activity.getWindow(), dark);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            View decor = activity.getWindow().getDecorView();
            int ui = decor.getSystemUiVisibility();
            if (dark) {
                ui |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            } else {
                ui &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            }
            decor.setSystemUiVisibility(ui);
        }
    }

    /**
     * 设置状态栏全透明
     *
     * @param activity 需要设置的activity
     */
    public static void setTransparent(Activity activity) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            return;
        }
        transparentStatusBar(activity);
        setRootView(activity);
    }

    /**
     * 设置根布局参数
     */
    private static void setRootView(Activity activity) {
        ViewGroup parent = (ViewGroup) activity.findViewById(android.R.id.content);
        for (int i = 0, count = parent.getChildCount(); i < count; i++) {
            View childView = parent.getChildAt(i);
            if (childView instanceof ViewGroup) {
                childView.setFitsSystemWindows(true);
                ((ViewGroup) childView).setClipToPadding(true);
            }
        }
    }

    /**
     * 使状态栏半透明
     * <p>
     * 适用于图片作为背景的界面,此时需要图片填充到状态栏
     *
     * @param activity 需要设置的activity
     */
    public static void setTranslucent(Activity activity) {
        setTranslucent(activity, DEFAULT_STATUS_BAR_ALPHA);
    }

    /**
     * 使状态栏半透明
     * <p>
     * 适用于图片作为背景的界面,此时需要图片填充到状态栏
     *
     * @param activity       需要设置的activity
     * @param statusBarAlpha 状态栏透明度
     */
    public static void setTranslucent(Activity activity,int statusBarAlpha) {
        setTransparent(activity);
        addTranslucentView(activity, statusBarAlpha);
    }


    /**
     * 添加半透明矩形条
     *
     * @param activity       需要设置的 activity
     * @param statusBarAlpha 透明值
     */
    public static void addTranslucentView(Activity activity,int statusBarAlpha) {
        addTranslucentViewWithColor(activity,Color.argb(statusBarAlpha, 0, 0, 0));
    }

    private static void addTranslucentViewWithColor(Activity activity,int color){
        ViewGroup contentView = activity.findViewById(android.R.id.content);
        View fakeTranslucentView = contentView.findViewById(FAKE_TRANSLUCENT_VIEW_ID);
        if (fakeTranslucentView != null) {
            if (fakeTranslucentView.getVisibility() == View.GONE) {
                fakeTranslucentView.setVisibility(View.VISIBLE);
            }
            fakeTranslucentView.setBackgroundColor(color);
        } else {
            contentView.addView(createTranslucentStatusBarView(activity, color), 0);
        }
    }

    private static View createTranslucentStatusBarView(Activity activity, int alpha) {
        return createTranslucentStatusBarViewWithColor(activity,Color.argb(alpha, 0, 0, 0));
    }

    private static View createTranslucentStatusBarViewWithColor(Activity activity,@ColorInt int color) {
        View statusBarView = new View(activity);
        LinearLayout.LayoutParams params =
                new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(activity));
        statusBarView.setLayoutParams(params);
        statusBarView.setBackgroundColor(color);
        statusBarView.setId(FAKE_TRANSLUCENT_VIEW_ID);
        return statusBarView;
    }

    /**
     * 获取状态栏高度
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        return context.getResources().getDimensionPixelSize(resourceId);
    }

    /**
     * 为头部是 ImageView 的界面设置状态栏透明(使用默认透明度)
     *
     * @param activity       需要设置的activity
     * @param needOffsetView 需要向下偏移的 View
     */
    public static void setTranslucentForImageView(Activity activity, View needOffsetView) {
        setTranslucentForImageView(activity, DEFAULT_STATUS_BAR_ALPHA, needOffsetView);
    }

    /**
     * 为头部是 ImageView 的界面设置状态栏透明
     *
     * @param activity       需要设置的activity
     * @param statusBarAlpha 状态栏透明度
     * @param needOffsetView 需要向下偏移的 View
     */
    public static void setTranslucentForImageView(Activity activity, int statusBarAlpha, View needOffsetView) {
        setTransparentForWindow(activity);
        addTranslucentView(activity, statusBarAlpha);
        if (needOffsetView != null) {
            Object haveSetOffset = needOffsetView.getTag(OFFSET_TAG);
            if (haveSetOffset != null && (Boolean) haveSetOffset) {
                return;
            }
            ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) needOffsetView.getLayoutParams();
            layoutParams.setMargins(layoutParams.leftMargin, layoutParams.topMargin + getStatusBarHeight(activity),
                    layoutParams.rightMargin, layoutParams.bottomMargin);
            needOffsetView.setTag(OFFSET_TAG, true);
        }
    }

    public static void setTranslucentForH5Container(Activity activity){
        setTransparentForWindow(activity);

        ViewGroup contentView = activity.findViewById(android.R.id.content);
        LinearLayout h5Container = null;
        if (contentView.getChildAt(0) != null){
            h5Container = (LinearLayout) ((ViewGroup)(contentView.getChildAt(0))).getChildAt(0);
        }
        if (h5Container == null){
            return;
        }

        View fakeTranslucentView = h5Container.getChildAt(0);
        if (fakeTranslucentView != null) {
            if (fakeTranslucentView.getVisibility() == View.GONE) {
                fakeTranslucentView.setVisibility(View.VISIBLE);
            }
            fakeTranslucentView.setBackgroundColor(Color.TRANSPARENT);
            LinearLayout.LayoutParams params =
                    new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(activity));
            fakeTranslucentView.setLayoutParams(params);
            activity.getWindow().getDecorView().requestLayout();
        }
    }

    /**
     * 为头部是 ImageView 的界面设置状态栏透明（界面滑动状态栏渐变时调用）
     *
     * @param activity       需要设置的activity
     * @param color 状态栏渐变颜色，如：Color.argb(statusBarAlpha, 0xff, 0xff, 0xff)
     * @param needOffsetView 需要向下偏移的 View
     */
    public static void setTranslucentForImageViewWithColor(Activity activity,@ColorInt int color, View needOffsetView){
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            return;
        }
        setTransparentForWindow(activity);
        addTranslucentViewWithColor(activity, color);
        if (needOffsetView != null) {
            Object haveSetOffset = needOffsetView.getTag(OFFSET_TAG);
            if (haveSetOffset != null && (Boolean) haveSetOffset) {
                return;
            }
            ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) needOffsetView.getLayoutParams();
            layoutParams.setMargins(layoutParams.leftMargin, layoutParams.topMargin + getStatusBarHeight(activity),
                    layoutParams.rightMargin, layoutParams.bottomMargin);
            needOffsetView.setTag(OFFSET_TAG, true);
        }
    }

    /**
     * flyme系统 状态栏图标为深色 和 魅族特定的文字风格
     *
     * @param window
     * @param dark
     * @return
     */
    public static boolean flymeSetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            try {
                WindowManager.LayoutParams lp = window.getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                window.setAttributes(lp);
                result = true;
            } catch (Exception e) {

            }
        }
        return result;
    }

    /**
     * miui系统状态栏 深色字体
     *
     * @param window
     * @param dark
     * @return
     */
    public static boolean miuiSetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            Class clazz = window.getClass();
            try {
                int darkModeFlag = 0;
                Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
                Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
                darkModeFlag = field.getInt(layoutParams);
                Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
                if (dark) {
                    extraFlagField.invoke(window, darkModeFlag, darkModeFlag);//状态栏透明且黑色字体
                } else {
                    extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
                }
                result = true;
            } catch (Exception e) {

            }
        }
        return result;
    }

    /**
     * Dialog设置状态栏透明
     * @param dialog
     */
    public static void setTranslucentStatusForDialog(Dialog dialog) {
        if(dialog==null)
            return;
        Window window = dialog.getWindow();
        if(window==null)
            return;
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    /**
     * 计算状态栏颜色
     *
     * @param color color值
     * @param alpha alpha值
     * @return 最终的状态栏颜色
     */
    private static int calculateStatusColor(@ColorInt int color, int alpha) {
        float a = 1 - alpha / 255f;
        int red = color >> 16 & 0xff;
        int green = color >> 8 & 0xff;
        int blue = color & 0xff;
        red = (int) (red * a + 0.5);
        green = (int) (green * a + 0.5);
        blue = (int) (blue * a + 0.5);
        return 0xff << 24 | red << 16 | green << 8 | blue;
    }

    /**
     * 移除状态栏高度的view
     * @param activity
     */
    public static void removeStatusBarView(Activity activity){
        ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content);
        View fakeTranslucentView = contentView.findViewById(FAKE_TRANSLUCENT_VIEW_ID);
        if (fakeTranslucentView != null) {
            contentView.removeView(fakeTranslucentView);
        }
    }


}
